#include "drv_usb.h"
#include "stm32g4xx_hal.h"
#include "usbd_core.h"
#include "usbd_cdc.h"
#include "util.h"

extern void USBD_IRQHandler(uint8_t busid);

PCD_HandleTypeDef hpcd_USB_FS;

void drvUsbInit(void)
{
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
    PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_HSI48;
    HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
    HAL_PWREx_DisableUCPDDeadBattery();
    __HAL_RCC_USB_CLK_ENABLE();

    hpcd_USB_FS.Instance = USB;
    hpcd_USB_FS.Init.dev_endpoints = 8;
    hpcd_USB_FS.Init.speed = PCD_SPEED_FULL;
    hpcd_USB_FS.Init.phy_itface = PCD_PHY_EMBEDDED;
    hpcd_USB_FS.Init.Sof_enable = DISABLE;
    hpcd_USB_FS.Init.low_power_enable = DISABLE;
    hpcd_USB_FS.Init.lpm_enable = DISABLE;
    hpcd_USB_FS.Init.battery_charging_enable = DISABLE;
    HAL_PCD_Init(&hpcd_USB_FS);

    // HAL_NVIC_SetPriority(USB_HP_IRQn, 0, 0);
    // HAL_NVIC_EnableIRQ(USB_HP_IRQn);
    HAL_NVIC_SetPriority(USB_LP_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USB_LP_IRQn);

    drvUsbStart();
}
void drvUsbDeinit(void)
{
    __HAL_RCC_USB_CLK_DISABLE();
    HAL_PCD_DeInit(&hpcd_USB_FS);
}

void USB_HP_IRQHandler(void)
{
    USBD_IRQHandler(0);
}

void USB_LP_IRQHandler(void)
{
    USBD_IRQHandler(0);
}

void drvUsbStart(void)
{
    __HAL_RCC_GPIOA_CLK_ENABLE();
    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.Pin = GPIO_PIN_15;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET);
}